package cn.chengpengper.shortlink.interceptor;

import cn.chengpengper.shortlink.constant.ShortLinkConstant;
import cn.chengpengper.shortlink.enums.BizCodeEnum;
import cn.chengpengper.shortlink.model.LoginUser;
import cn.chengpengper.shortlink.util.CommonUtil;
import cn.chengpengper.shortlink.util.JsonData;
import cn.chengpengper.shortlink.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author huchengpeng
 * @version v1.0.0
 * @date 2023/9/2 18:40
 * @description 登录拦截器
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<LoginUser> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (HttpMethod.OPTIONS.toString().equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return true;
        }
        // 从Header或者请求参数中获取token
        String token = request.getHeader(ShortLinkConstant.TOKEN);
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(ShortLinkConstant.TOKEN);
        }
        if (StringUtils.isBlank(token)) {
            CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
            return false;
        }

        Claims claims = JwtUtil.decryptJsonWebToken(token);
        if (Objects.isNull(claims)) {
            CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
            return false;
        }

        Long accountNo = Long.parseLong(claims.get(JwtUtil.ACCOUNT_NO).toString());
        String headImg = claims.get(JwtUtil.HEAD_IMG).toString();
        String username = claims.get(JwtUtil.USERNAME).toString();
        String phone = claims.get(JwtUtil.PHONE).toString();
        String mail = claims.get(JwtUtil.MAIL).toString();
        String auth = claims.get(JwtUtil.AUTH).toString();

        LoginUser loginUser = LoginUser.builder()
                .username(username)
                .accountNo(accountNo)
                .phone(phone)
                .headImg(headImg)
                .mail(mail)
                .auth(auth).build();

        threadLocal.set(loginUser);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        threadLocal.remove();
    }
}
